/**
 * @Description: 微信公众号对接
 * @Version: 1.0
 * @Author: 琴时
 * @Date: 2021-12-28 15:08:16
 * @LastEditors: 琴时
 * @LastEditTime: 2023-04-21 12:28:30
 */

import axios from 'axios'
import express from 'express'
import wechat from 'wechat' //微信公共平台自动回复消息接口服务中间件
import WeChatAPI from 'co-wechat-api'
import config from '../../config'
import AccessToken from '../../db/mongo/AccessToken'
import Token from '../../db/mongo/Token'
const { weChat } = config
const { appId, appSecret } = weChat
import newWeChat from '../../src/util_wechat'
const router = express.Router()
const API = new newWeChat(
  appId,
  appSecret,
  async () => {
    // 先获取token
    const res = await AccessToken.getAccessToken()
    console.log('测试get:', res)
    return res
  },
  async token => {
    console.log('测试set:', token)
    // 获取没有返回执行
    return await AccessToken.setAccessToken(token)
  }
)

const api = new WeChatAPI(
  appId,
  appSecret,
  async () => {
    // 先获取token
    const res = await AccessToken.getAccessToken()
    console.log('测试get:', res)
    return res
  },
  async token => {
    console.log('测试set:', token)
    // 获取没有返回执行
    return await AccessToken.setAccessToken(token)
  }
)
router.use((req, res, next) => {
  console.log('测试API:', API.createMenu())
  // console.log('测试api:',api)

  next()
})

import OAuth from 'co-wechat-oauth'
const oauth = new OAuth(
  appId,
  appSecret,
  async openid => {
    console.log('测试get', openid)
    return await Token.getToken(openid)
  },
  async (openid, token) => {
    console.log('测试set:', openid, token)
    return await Token.setToken(openid, token)
  }
)
// token缓存
const tokenCache = {
  access_token: '',
  updateTime: Date.now(),
  expires_in: 7200,
}
const wxDomain = 'https://api.weixin.qq.com' //微信公众号域名

// 获取access_token
router.get('/getAccessToken', async (req, res, next) => {
  // const result = await newWc.getAccessToken()
  // console.log('测试newWc:', newWc)
  console.log('测试getAccessToken:')
  res.sendResult(200, 'success', null)
})

router.get('/wxAuthorize', (req, res, next) => {
  const { referer } = req.headers
  const state = 'STATE' //可自定义的携带参数体
  const scope = 'snsapi_userinfo'
  const url = oauth.getAuthorizeURL(`${referer.split('?')[0]}`, state, scope)
  // console.log('测试url:', url)
  res.redirect(url)
})

router.get('/getOpenId', async (req, res, next) => {
  const { code } = req.query
  try {
    const token = await oauth.getAccessToken(code)
    // console.log('测试token:', token)
    const { access_token, openid } = token.data
    return res.sendResult(200, 'success', openid)
  } catch (error) {
    console.log('测试error:', error)
    return res.sendResult(500, '系统繁忙', null)
  }
})

router.get('/getInfo', async (req, res, next) => {
  const { openid } = req.query
  try {
    const userInfo = await oauth.getUser(openid)
    return res.sendResult(200, 'success', userInfo)
  } catch (error) {
    console.log('测试error:', error)
    return res.sendResult(500, '系统繁忙', null)
  }
})

router.get('/getJsconfig', async (req, res, next) => {
  try {
    // const { referer } = req.headers
    // console.log('测试referer:',referer)
    const result = await api.getJsConfig(req.query.url)
    console.log('测试:', result)
    return res.sendResult(200, 'success', result)
  } catch (error) {
    console.log('测试error:', error)
    return res.sendResult(500, '系统繁忙', null)
  }
})

// 获取关注列表
router.get('/getFollowers', async (req, res, next) => {
  const path = '/cgi-bin/user/get' //请求路径
  const params = `?access_token=${req.tokenCache.access_token}` //请求参数
  const url = wxDomain + path + params
  const result = await axios.get(url)
  // console.log('测试:',result)
  res.sendResult(200, 'success', result.data)
})

// 调库获取关注列表
router.get('/getApiFollowers', async (req, res, next) => {
  let result = await api.getFollowers()
  // console.log('测试101:', result)
  result = await api.batchGetUsers(result.data.openid, 'zh_CN')
  // console.log('测试result:',result)
  res.sendResult(200, 'success', result)
})

// 获取缓存
router.get('/getCache', (req, res, next) => {
  console.log('测试tokenCache:', tokenCache)
  res.sendResult(200, 'success', tokenCache)
})
// 校验微信url接口
router.all(
  '/',
  wechat(weChat, function (req, res, next) {
    // 微信输入信息都在req.weixin上
    var message = req.weixin
    console.log('测试:', message, req.query)

    switch (message.Content) {
      case 'ds':
        res.reply('hehe')
        break
      case 'tt':
        res.reply({
          content: 'text object',
          type: 'text',
        })
        break
      case 'hh':
        res.reply({
          type: 'music',
          content: {
            title: '来段音乐吧',
            description: '一无所有',
            musicUrl: 'http://mp3.com/xx.mp3',
            hqMusicUrl: 'http://mp3.com/xx.mp3',
            thumbMediaId: 'thisThumbMediaId',
          },
        })
        break
      case '001':
        res.sendResult(200, '', null)
        break
      default:
        res.reply([
          {
            title: '你来我家接我吧',
            description: '这是女神与高富帅之间的对话',
            picurl: 'https://www.baidu.com/img/bd_logo1.png',
            url: 'https://www.baidu.com/',
          },
        ])
        break
    }
  })
)

module.exports = router
